<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <meta name="viewport"
    content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover" />
</head>

<body>
  <div class="content">
    <div>
      <button onclick="playAudio()">播放音频</button>
      <button onclick="deleteCatch()">删除缓存</button>
    </div>
    <button onclick="void(location.reload())">刷新网页</button>
  </div>
  <script>
    const audioUrl = 'https://www.*******************/static/audio/music.mp3';
    function deleteCatch() {
      const request = indexedDB.open('audioCacheDB', 1);
      request.onsuccess = function (event) {
        const db = event.target.result;
        const transaction = db.transaction(['audioCache'], 'readwrite');
        const objectStore = transaction.objectStore('audioCache');
        const deleteRequest = objectStore.delete(audioUrl);
        // 监听删除成功事件
        deleteRequest.onsuccess = function (event) {
          alert('缓存删除成功');
        };
  
        // 监听删除失败事件
        deleteRequest.onerror = function (event) {
          alert('缓存删除失败');
        };
      }

    }
    function playAudio() {

      const request = indexedDB.open('audioCacheDB', 1);

      request.onerror = function (event) {
        console.error('数据库打开错误', event.target.error);
        showError('音频播放出现问题，请检查网络连接或稍后再试。');
      };

      request.onsuccess = function (event) {
        const db = event.target.result;
        const transaction = db.transaction(['audioCache'], 'readonly');
        const objectStore = transaction.objectStore('audioCache');
        const getRequest = objectStore.get(audioUrl);

        getRequest.onsuccess = function () {
          if (getRequest.result) {
            showError('取得缓存，本次播放不耗费流量...');
            // 如果有缓存，从缓存中读取播放
            console.log("111111111111111", getRequest.result)
            const audioBlob = new Blob([getRequest.result.data], { type: 'audio/mpeg' });
            console.log("222222222222222", audioBlob)
            const audio = new Audio(URL.createObjectURL(audioBlob));
            console.log("333333333333333", audio)
            audio.play();
          } else {
            // 如果没有缓存，从服务器请求并缓存
            fetch(audioUrl).then((response) => {
              console.log("response", response);
              return response.arrayBuffer();
            }).then(data => {
              showError('无缓存！下载后开始播放...');
              console.log("4444444444444444444", data)
              const transaction = db.transaction(['audioCache'], 'readwrite');
              const objectStore = transaction.objectStore('audioCache');
              const audioData = {
                url: audioUrl,
                data: new Uint8Array(data)
              };
              console.log("5555555555555555555", audioData)
              objectStore.put(audioData);
              const audioBlob = new Blob([data], { type: 'audio/mpeg' });
              const audio = new Audio(URL.createObjectURL(audioBlob));
              audio.play();
            })
              .catch(error => {
                console.error('音频资源获取错误', error);
                showError('无法获取音频资源，请检查网络连接或稍后再试。');
              });
          }
        };
      };

      request.onupgradeneeded = function (event) {
        const db = event.target.result;
        const objectStore = db.createObjectStore('audioCache', { keyPath: 'url' });
      };

      function showError(message) {
        const errorElement = document.createElement('div');
        errorElement.style.marginTop = '20px';
        errorElement.textContent = message;
        document.body.appendChild(errorElement);
      }

      // 检查浏览器是否支持 IndexedDB
      if (!window.indexedDB) {
        showError('您的浏览器不支持 IndexedDB，无法使用缓存功能。');
      }
    }
  </script>
</body>

<style>
  .content{
    display: flex;
    justify-content: space-between;
  }
  button {
    padding: 5px 10px;
    font-size: 17px;
  }
</style>

</html>